package service

import (
	"pq/models"
	"pq/repository"
	"strconv"
)

type SimuItemService struct{

}
func (sis SimuItemService) GetSimuWithResrouce(simuId string,tm string) ([]map[string]interface{},int){
	repo := repository.SimuItemRespository{}
	simus,total := repo.GetSimus(simuId)
	finals := []map[string]interface{}{}
	var resources []models.PqCsTestResource
	var resourceMap  = map[int] []map[string] interface{}{}
	var resourceBody = map[int] string{}
	for _,simu := range simus{
		if simu["pq_cs_test_resource_id"].(string) == "0" {
			finals = append(finals, map[string]interface{}{
				"id":              simu["id"],
				"simu_type":		"0",
				"type":            simu["type"],
				"body":            simu["body"],
				"analysis":        simu["analysis"],
				"answer_data":     simu["answer_data"],
				"is_answered":     simu["is_answered"],
				"is_answer_right": simu["is_answer_right"],
				"score":           simu["score"],
				"ordering":        simu["ordering"],
				"library_id":      simu["pq_cs_test_simu_library_id"],
				"item_id": 		   simu["pq_cs_test_item_id"],
				"resource_id":     simu["pq_cs_test_resource_id"],
				"is_collected" :  simu["is_collected"],
				"section" : simu["section"],
				"answer_ids" : simu["answer_choose_data"],
			})
		}else{
			resource_id := simu["pq_cs_test_resource_id"].(string)
			rid,err := strconv.Atoi(resource_id)
			if err == nil {
				if _,ok := resourceMap[rid];!ok {
					rs := repo.GetResource(rid)
					resources = append(resources, rs)
					resourceBody[rid] = rs.Body
				}
				resourceMap[rid] = append(resourceMap[rid], map[string]interface{}{
					"id":              simu["id"],
					"type":            simu["type"],
					"body":            simu["body"],
					"analysis":        simu["analysis"],
					"answer_data":     simu["answer_data"],
					"is_answered":     simu["is_answered"],
					"is_answer_right": simu["is_answer_right"],
					"score":           simu["score"],
					"ordering":        simu["ordering"],
					"library_id":      simu["pq_cs_test_simu_library_id"],
					"item_id": 		   simu["pq_cs_test_item_id"],
					"resource_id":     simu["pq_cs_test_resource_id"],
					"is_collected" : simu["is_collected"],
					"resource_body" : resourceBody[rid],
					"section" : simu["section"],
				})
			}
		}
	}

	for _,resource := range resources {
		if tm == "flat" {
			for _,rs := range resourceMap[resource.Id]{
				finals = append(finals,rs)
			}
		} else{
			finals = append(finals, map[string]interface{}{
				"id":         resource.Id,
				"type":       "2",
				"body":       resource.Body,
				"library_id": resource.PqCsTestLibraryId,
				"questions":  resourceMap[resource.Id],
			})
		}
	}
	return finals,total
}

func (sis SimuItemService) Collected(id int,val int,uid string)(int64,error){
	repo := repository.SimuItemRespository{}
	return repo.Collect(id,val,uid)
}

func (sis SimuItemService) ReOrder(simuLibId int){
	repo := repository.SimuItemRespository{}
	repo.ReOrder(simuLibId)
}